# -*- coding: utf-8 -*-
"""
xfree.cli.themes
~~~~~~~~~~~~~~~~~~

这个模块包含所有与主题相关的命令。

:copyright: (c) 2016 by the xfree Team.
:license: BSD，查看 LICENSE 获取更多详细信息。
"""

import os
import shutil
import sys

import click
from flask import current_app
from flask_themes2 import get_theme, get_themes_list

from xfree.cli.main import xfree
from xfree.cli.utils import get_cookiecutter, validate_theme
from xfree.utils.settings import xfree_config


@xfree.group()
def themes():
    """主题命令子组。"""
    pass


@themes.command("list")
def list_themes():
    """列出所有已安装的主题。"""
    click.secho("[+] 正在列出所有已安装的主题...", fg="cyan")

    # 获取当前活动主题
    active_theme = get_theme(xfree_config["DEFAULT_THEME"])
    # 获取所有可用主题列表，并排除活动主题
    available_themes = set(get_themes_list()) - set([active_theme])

    click.secho("[+] 活动主题：", fg="blue", bold=True)
    click.secho(
        "    - {} (版本 {})".format(active_theme.name, active_theme.version),
        bold=True,
    )

    click.secho("[+] 可用主题：", fg="yellow", bold=True)
    for theme in available_themes:
        click.secho(
            "    - {} (版本 {})".format(theme.name, theme.version), bold=True
        )


@themes.command("new")
@click.option(
    "--template",
    "-t",
    type=click.STRING,
    default="https://github.com/sh4nks/cookiecutter-xfree-theme",
    help="指向一个 cookiecutter 模板的路径或一个有效的 Git 仓库地址。",
)
@click.option(
    "--out-dir",
    "-o",
    type=click.Path(),
    default=None,
    help="新的 xfree 主题的保存位置。",
)
@click.option(
    "--force",
    "-f",
    is_flag=True,
    default=False,
    help="如果输出目录已存在，则覆盖其内容。",
)
def new_theme(template, out_dir, force):
    """基于 cookiecutter 主题模板创建一个新主题。默认使用这个模板：
    https://github.com/sh4nks/cookiecutter-xfree-theme。
    它可以接受文件系统中的有效路径或者包含 cookiecutter 模板的 Git 仓库 URL。
    """
    cookiecutter = get_cookiecutter()

    if out_dir is None:
        out_dir = click.prompt(
            "保存主题的位置", default=os.path.join(current_app.root_path, "themes")
        )

    r = cookiecutter(template, output_dir=out_dir, overwrite_if_exists=force)
    click.secho("[+] 在 {} 创建了新主题。".format(r), fg="green", bold=True)


@themes.command("remove")
@click.argument("theme_identifier")
@click.option(
    "--force",
    "-f",
    default=False,
    is_flag=True,
    help="无需确认直接删除主题。",
)
def remove_theme(theme_identifier, force):
    """从文件系统中删除一个主题。"""
    validate_theme(theme_identifier)
    if not force and not click.confirm(click.style("你确定吗？", fg="magenta")):
        sys.exit(0)

    theme = get_theme(theme_identifier)
    click.secho("[+] 正在从文件系统中删除主题...", fg="cyan")
    shutil.rmtree(theme.path, ignore_errors=False, onerror=None)